import { Component, OnInit, Input } from '@angular/core';
import { NzMessageService, UploadFile, NzModalService, UploadFilter } from 'ng-zorro-antd';

import { ApiService } from 'src/app/core/service/api.service';

import { LicenseModalComponent } from '../../data-center-modal/license-modal/license-modal.component';
import { LibraryModalComponent } from '../../data-center-modal/library-modal/library-modal.component';
import { CveModalComponent } from '../../data-center-modal/cve-modal/cve-modal.component';
import { ContainerModalComponent } from '../../data-center-modal/container-modal/container-modal.component';
import { AddBaselineComponent } from '../../data-center-modal/add-baseline/add-baseline.component';
import { LibraryService } from 'src/app/core/service/library.service';

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.scss']
})
export class FileUploadComponent implements OnInit {
  @Input() title: string;
  @Input() icon: string;
  @Input() total: number;
  @Input() useCount: number;

  uploading = false;

  fileList: UploadFile[] = []; // 文件列表
  filters: UploadFilter[] = [{  // 过滤文件
    name: 'type',
    fn: (fileList: UploadFile[]) => {
      this.filter(fileList);
      return fileList;
    }
  }];

  constructor(
    private apiService: ApiService,
    private modalService: NzModalService,
    private message: NzMessageService,
    private libraryService: LibraryService
  ) {
  }

  filter(fileList: UploadFile[]): any {
    // tslint:disable-next-line:no-bitwise
    const xmlFiles = fileList.filter(w => ~['text/xml'].indexOf(w.type));
    // tslint:disable-next-line:no-bitwise
    const jsonFiles = fileList.filter(w => ~['application/json'].indexOf(w.type));
    if (xmlFiles.length !== fileList.length && jsonFiles.length !== fileList.length) {
      this.message.error(`包含文件格式不正确，只支持 json和xml 格式`);
      return xmlFiles;
    }
  }


  createComponentModal(type: string): void {
    if (type === '组件') {
      const modal = this.modalService.create({
        nzTitle: '添加组件',
        nzContent: LibraryModalComponent,
        nzComponentParams: {
          title: 'title in component',
          subtitle: 'component sub title，will be changed after 2 sec'
        },
        nzFooter: null
      });
    }

    if (type === 'License') {
      const modal = this.modalService.create({
        nzTitle: '添加许可',
        nzContent: LicenseModalComponent,
        nzComponentParams: {
          title: 'title in LicenseModalComponent',
          subtitle: 'component sub title，will be changed after 2 sec'
        },
        nzFooter: null
      });
    }

    if (type === 'CVE') {
      const modal = this.modalService.create({
        nzTitle: '新增CVE',
        nzWidth: '800',
        nzContent: CveModalComponent,
        nzComponentParams: {
          title: 'title in CveModalComponent',
          subtitle: 'component sub title，will be changed after 2 sec'
        },
        nzFooter: null
      });
    }

    if (type === 'CNNVD') {
      const modal = this.modalService.create({
        nzTitle: '新增CNNVD',
        nzWidth: '800',
        nzContent: CveModalComponent,
        nzComponentParams: {
          title: 'title in CveModalComponent',
          subtitle: 'component sub title，will be changed after 2 sec'
        },
        nzFooter: null
      });
    }

    if (type === '容器') {
      const modal = this.modalService.create({
        nzTitle: '添加容器',
        nzContent: ContainerModalComponent,
        nzComponentParams: {
          title: 'title in ContainerModalComponent',
          subtitle: 'component sub title，will be changed after 2 sec'
        },
        nzFooter: null
      });
    }

    if (type === '基线') {
      const modal = this.modalService.create({
        nzTitle: '添加基线',
        nzContent: AddBaselineComponent,
        nzComponentParams: {
        },
        nzFooter: null
      });
    }
  }

  beforeUpload = (file: UploadFile): boolean => {
    this.fileList = this.fileList.concat(file);
    return false;
  }

  handleUpload(): void {
    console.log('=== title ===>', this.title);
    const formData = new FormData();
    this.fileList.forEach((file: any) => {
      formData.append('fileName', file);
    });
    this.uploading = true;
    if (this.title === '组件') { this.fileUpload('/thirdPartyLib/data/upload', formData); }
    if (this.title === 'License') { this.fileUpload('/license/data/upload', formData); }
    if (this.title === '漏洞') { this.fileUpload('/data/cveandcnnvd/upload', formData); }
    if (this.title === '容器基线') { this.fileUpload('/data/baselineorcontainer/upload', formData); }
  }


  fileUpload(path: string, formData: FormData) {
    this.apiService.fileUpLoad(path, formData).subscribe((uploadResult) => {
      // this.result = result;   // 返回的结果
      console.log('== fileUpload.返回了没？ ==');  // 如果出错，没有
      console.log('== fileUpload.uploadResult ==', uploadResult);
      if (uploadResult.status === 1) {
        this.message.success('上传成功!', {
          nzDuration: 10000
        });
        this.uploading = false;
      }
      if (uploadResult.status === 0) {
        this.message.error('上传失败!', {
          nzDuration: 10000
        });
        this.uploading = false;
      }
    });
  }

  downloadJar(title: string, type: string) {
    console.log('=== Janine.downloadJar().title + type ===>', title + 'type ==>' + type);
    if (title === '组件') {
      this.downloadFiles(title, type, 'jar');
    }
    if (title === 'License') {
      this.downloadFiles(title, type, 'license');
    }
    if (title === 'cve') {
      this.downloadFiles('cve', type, 'cve');
    }
  }

  downloadFiles(title: string, type: string, filesName: string) {
    this.libraryService.downloadJar(title, type).subscribe((data) => {
      const agentFile = new Blob([data], { type: 'application/' + type });
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(agentFile);
      } else {
        const link = document.createElement('a');
        document.body.appendChild(link);
        link.style.visibility = 'hidden';
        link.href = window.URL.createObjectURL(agentFile);
        link.download = filesName + '.' + type;
        link.click();
        document.body.removeChild(link);
      }
    });
  }

  ngOnInit() { }


}
